#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanAyshxrmzf2Cf3Policy(BaseTaxPolicySpider):
    name = 'henan_ayshxrmzf_2cf3_policy'
    
    province = '河南省'
    city = '安阳市'
    county = '滑县'
    park = ''
    source = '安阳市滑县人民政府'
    url = 'http://www.hnhx.gov.cn/portal/zwgk/gfxwj/hzb/A00020802index_1.htm'
    
    def start_requests(self):
        url = 'http://www.hnhx.gov.cn/portal/zwgk/gfxwj/hzb/A00020802index_1.htm'
        yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath("//ul/li[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5] | //dl/dt[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::dt[string-length(string(.))>=5] | //tr/td[not(@id)]//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""string(.)""").re_first(r"""共\s*(\d+)\s*条""")
            for page_num in range(1, int(total_page) // 20):
                yield response.follow(re.sub(r"(.*/[A-Z0-9]+)(index?)(_\d+)\.", r"\g<1>\g<2>_{}.".format(page_num), response.url), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_ayshxrmzf_2cf3_policy".split())
